
#include "mutex.h"


namespace	common
{
	mutex::mutex()
		: cs_( nullptr )
	{
	}

	mutex::~mutex()
	{
		destroy();
	}

	bool	mutex::create( size_t spin_count )
	{
		assert( cs_ == nullptr );
		if( cs_ != nullptr )
		{
			return false;
		}

		cs_ = new CRITICAL_SECTION;
		if( cs_ == nullptr )
		{
			return false;
		}

		DWORD spin = static_cast< DWORD >( spin_count );
		if( ::InitializeCriticalSectionAndSpinCount( cs_, spin ) == FALSE )
		{
			delete cs_;
			cs_ = nullptr;
			return false;
		}

		return true;
	}

	void	mutex::destroy()
	{
		if( cs_ != nullptr )
		{
			::DeleteCriticalSection( cs_ );

			delete cs_;
			cs_ = nullptr;
		}
	}

	bool	mutex::lock()
	{
		assert( cs_ != nullptr );
		if( cs_ != nullptr )
		{
			::EnterCriticalSection( cs_ );
			return true;
		}

		return false;
	}

	bool	mutex::try_lock()
	{
		assert( cs_ != nullptr );
		if( cs_ != nullptr )
		{
			if( ::TryEnterCriticalSection( cs_ ) == FALSE )
			{
				return false;
			}

			return true;
		}

		return false;
	}

	bool	mutex::unlock()
	{
		assert( cs_ != nullptr );
		if( cs_ != nullptr )
		{
			::LeaveCriticalSection( cs_ );
			return true;
		}

		return false;
	}
}
